#include "stdafx.h"
#include "ui_sysfont_map.h"

#include <atlbase.h>

_SSL_BEGIN
_SSUIL_BEGIN

UISysFontMap::UISysFontMap()
{
	Rebuild();
}

UISysFontMap::~UISysFontMap()
{

}

void UISysFontMap::Rebuild()
{
	name_path_map_.clear();

	CRegKey regkey;
	if(regkey.Open(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"),
		KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS) != ERROR_SUCCESS)
		return;
	TCHAR name[MAX_PATH] = {0};
	TCHAR value[MAX_PATH] = {0};
	for(DWORD idx=0;idx<1000;idx++)
	{
		DWORD len = SS_DIMOF(name);
		LONG ret = 0;
		ret = ::RegEnumValue(regkey, idx, name, &len, NULL, NULL, NULL, NULL);
		// ret = regkey.EnumKey(idx, name, &len, NULL);
		if(ret ==  ERROR_NO_MORE_ITEMS)
			break;
		if(ret != ERROR_SUCCESS)
			continue;

		ULONG len2 = SS_DIMOF(value);
		ret = regkey.QueryStringValue(name, value, &len2);
		if(ret != ERROR_SUCCESS || _tcslen(value) == 0)
			continue;

		tstring nm_l = name;
		str_lower(nm_l);
		tstrings nms = str_split(nm_l, _T('('));
		nm_l = nms[0];
		nms = str_split(nm_l, _T('&'));
		for(tstrings::iterator iter=nms.begin(); iter!=nms.end(); iter++)
		{
			nm_l = *iter;
			str_trim(nm_l, NULL);
			if(!nm_l.empty())
			{
				name_path_map_[nm_l] = value;
			}
		}
	}
}

tstring UISysFontMap::FontPathFromName(const tstring &name)
{
	tstring nm_l = name;
	str_lower(nm_l);
	str_trim(nm_l, NULL);
	tstring_tstring_map::iterator iter = name_path_map_.find(nm_l);
	if(iter == name_path_map_.end())
		return _T("");

	tchar win_dir[MAX_PATH] = {0};
	::GetWindowsDirectory(win_dir, SS_DIMOF(win_dir));
	tstring font_file = win_dir;
	file_path_append(font_file, _T("Fonts\\"));
	file_path_append(font_file, iter->second);

	return font_file;
}

_SSUIL_END
_SSL_END
